<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { useAccess } from '@vben/access';
import { Button, message, Switch } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getClientListApi, getOrderListApi, handleOrderdataApi } from '#/api';
import { MdiAdd, MdiRefresh, MdiDownload } from '@vben/icons';

import orderForm from './order.vue';
import descriptionForm from './desc.vue';
import { testItemsOptions } from './schemas';

interface RowType {
  orderNo: string;
  clientName: string;
  contactPerson: string;
  sampleName: string;
  modelSpec: string;
  quantity: string;
  testItems: string;
  specialReq: string;
  sampleHandling: string;
  testCycle: string;
  serviceType: string;
  remarks: string;
  orderDate: string;
}

const loadingV = ref(false); // 记录当前是否进入loading状态
const orderFormRef = ref();
const descriptionRef = ref();
const { hasAccessByCodes } = useAccess();

const formOptions: VbenFormProps = {
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 默认展开
  collapsed: false,
  fieldMappingTime: [['date', ['start', 'end']]],
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        // mode: 'multiple',
        placeholder: '请选择',
        allowClear: true,
        afterFetch: (data) => {
          if (data.length > 0) {
            return data.map((item: any) => ({
              label: item.clientName,
              value: item.clientName,
            }));
          } else {
            return [];
          }
        },
        api: getClientListApi,
      },
      label: '委托单位', // $t('page.auth.forgetPassword'),
      fieldName: 'clientName',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
        addonBefore: 'RT/JC-WT-',
      },
      fieldName: 'orderNo',
      label: '委托单编号',
    },
  ],
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-3',
};

const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { fixed: 'left', field: 'checkbox', type: 'checkbox', title: '全选', width: 75 },
    { fixed: 'left', field: 'seq', type: 'seq', title: '序号', width: 50 },
    { fixed: 'left', field: 'orderNo', title: '委托单编号', width: 180 },
    { field: 'clientName', title: '委托单位', width: 200 },
    { field: 'orderDate', title: '委托时间', width: 120, formatter: 'formatDate' },
    { field: 'contactPerson', title: '联系人', width: 100 },
    { field: 'sampleName', title: '样品名称', width: 150 },
    { field: 'modelSpec', title: '型号规格', width: 150 },
    { field: 'quantity', title: '数量', width: 80 },
    { field: 'testItems', title: '检测项目', width: 120 },
    { field: 'receiveStatus', title: '收样状态', slots: { default: 'receiveStatus' }, width: 120 },
    { field: 'specialReq', title: '特殊要求', width: 180 },
    { field: 'sampleHandling', title: '样品处理方式', width: 120 },
    { field: 'testCycle', title: '测试周期', width: 280 },
    { field: 'serviceType', title: '服务类型', width: 80 },
    { field: 'remarks', title: '备注', width: 200 },
    { fixed: 'right', field: 'action', title: '操作', visible: true, slots: { default: 'action' }, width: 180 },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const values = formValues;
        // 将如果formValues.orderNo不为空，则格式化为WTC-开头，数字位数不足四位，前面补0
        if (values.orderNo) {
          values.orderNo = 'RT/JC-WT-' + values.orderNo;
        }
        const result = await getOrderListApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          ...values,
        });
        // 如果result.message不为ok或undefined，则使用message显示result.message
        if (result.message === '未查询到匹配的数据') {
          message.info(result.message);
        } else if (result.message !== 'ok' && result.message !== undefined) {
          message.error(result.message);
        }

        // 转译数据
        const testItemsOptionsMap = testItemsOptions.reduce((acc: any, cur: any) => {
          acc[cur.value] = cur.label;
          return acc;
        }, {});
        result.items = result.items.map((item: any) => {
          return {
            ...item,
            testItems: testItemsOptionsMap[item.testItems],
            sampleHandling: item.sampleHandling ? '样品退回' : '检测单位自行处理',
            serviceType: item.serviceType ? '加急' : '普通',
            receiveStatus: item.receiveStatus === 1 ? true : false,
          };
        });
        return result;
      },
    },
  },
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  showOverflow: false,
  pagerConfig: {},
  toolbarConfig: {
    export: true,
    refresh: true,
    refreshOptions: {
      code: 'reload',
    },
    search: true,
    zoom: true,
    custom: true,
  },
  customConfig: {
    mode: 'modal',
    checkMethod({ column }) {
      return !['checkbox', 'seq', 'orderNo', 'action'].includes(column.field);
    },
  },
  rowConfig: {
    isHover: true,
  },
  columnConfig: {
    resizeable: true,
  },
  resizeableConfig: {
    isDblClickAutoWidth: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  // 默认显示搜索表单
  showSearchForm: true,
});

/*==================================函数过程=========================================*/
// 操作
const handleAction = async (action: 'view' | 'new' | 'edit' | 'saveas' | 'download' | 'update', record: any) => {
  loadingV.value = true;
  // 延迟0.5秒，确保全局loading生效，防止用户再次操作
  await new Promise((resolve) => setTimeout(resolve, 500));

  if (action === 'view') {
    // 处理查看
    descriptionRef.value.setData({
      record,
    });
    descriptionRef.value.open();
  } else if (action === 'download') {
    // 处理下载
    // const selectedRows = await gridApi.grid.getCheckboxRecords();
    // if (selectedRows.length > 0) {
    // gridApi.grid.setCheckboxRow(rows, checked);
    message.success('下载成功');
    // } else {
    //   message.info('请至少选择一行数据');
    // }
  } else if (action === 'update') {
    const res = await handleOrderdataApi('update', record.orderNo, { receiveStatus: record.receiveStatus });
    if (res.code === 0) {
      message.success('更新成功');
      gridApi.reload();
    } else {
      message.error('更新失败');
    }
  } else {
    // 处理其他操作
    orderFormRef.value.setData({
      record,
      whichAction: action,
      gridApi,
    });
    orderFormRef.value.open();
  }

  await new Promise((resolve) => setTimeout(resolve, 500));
  loadingV.value = false;
};

// 刷新并返回第一页
const handleReload = async () => {
  gridApi.reload();
};
// 刷新当前页面
// const handleRefresh = async () => {
//   gridApi.query()
// }
</script>
<template>
  <Page v-loading="loadingV" auto-content-height>
    <Grid>
      <template #action="{ row }">
        <Button class="px-1" type="link" @click="handleAction('view', row)">查看</Button>
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleAction('edit', row)"
          >编辑</Button
        >
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleAction('saveas', row)"
          >另存</Button
        >
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleAction('download', row)"
          >下载</Button
        >
      </template>
      <template #receiveStatus="{ row }">
        <!-- <Tag :bordered="false" :color="row.receiveStatus ? 'success' : 'warning'">
          {{ row.receiveStatus ? '已收样' : '未收样' }}
        </Tag> -->
        <Switch
          v-model:checked="row.receiveStatus"
          @beforechange="handleAction('update', row)"
          checked-children="已收样"
          un-checked-children="未收样"
        />
      </template>
      <template #toolbar-actions>
        <Button
          v-if="hasAccessByCodes(['msdsNew'])"
          class="mr-2 flex items-center justify-center"
          type="primary"
          @click="handleAction('new', {})"
        >
          <!-- 20像素大小的图标 -->
          <MdiAdd class="size-4" />
          新增
        </Button>
        <Button
          class="mr-2 flex items-center justify-center"
          type="primary"
          style="background-color: #0bd092"
          @click="handleReload"
        >
          <MdiRefresh class="size-4" />
          刷新
        </Button>
        <Button
          class="mr-2 flex items-center justify-center"
          type="primary"
          style="background-color: #ff9940"
          @click="handleReload"
        >
          <MdiDownload class="size-4" />
          下载
        </Button>
      </template>
    </Grid>
    <orderForm ref="orderFormRef" />
    <descriptionForm ref="descriptionRef" />
  </Page>
</template>
